home *** CD-ROM | disk | FTP | other *** search
/ Acorn RISC PD-CD 1 / Acorn RISC PD-CD 1.iso / languages / gawk / c / main < prev    next >
Encoding:
Text File  |  1991-02-05  |  12.5 KB  |  562 lines

  1. /*
  2.  * main.c -- Expression tree constructors and main program for gawk. 
  3.  */
  4.  
  5. /* 
  6.  * Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc.
  7.  * 
  8.  * This file is part of GAWK, the GNU implementation of the
  9.  * AWK Progamming Language.
  10.  * 
  11.  * GAWK is free software; you can redistribute it and/or modify
  12.  * it under the terms of the GNU General Public License as published by
  13.  * the Free Software Foundation; either version 1, or (at your option)
  14.  * any later version.
  15.  * 
  16.  * GAWK is distributed in the hope that it will be useful,
  17.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  19.  * GNU General Public License for more details.
  20.  * 
  21.  * You should have received a copy of the GNU General Public License
  22.  * along with GAWK; see the file COPYING.  If not, write to
  23.  * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  24.  */
  25. #include "kernel.h"
  26.  
  27. #include "awk.h"
  28. #include "patchlevel.h"
  29. #include <signal.h>
  30. #include "swis.h"
  31.  
  32. extern int yyparse();
  33. extern void do_input();
  34. extern int close_io();
  35. extern void init_fields();
  36. extern NODE *node();
  37.  
  38. static void usage();
  39. static void set_fs();
  40. static void init_vars();
  41. static void init_args();
  42. static NODE *spc_var();
  43. static void pre_assign();
  44. static void copyleft();
  45.  
  46. /* These nodes store all the special variables AWK uses */
  47. NODE *FS_node, *NF_node, *RS_node, *NR_node;
  48. NODE *FILENAME_node, *OFS_node, *ORS_node, *OFMT_node;
  49. NODE *FNR_node, *RLENGTH_node, *RSTART_node, *SUBSEP_node;
  50. NODE *ENVIRON_node, *IGNORECASE_node;
  51. NODE *ARGC_node, *ARGV_node;
  52.  
  53. /*
  54.  * The parse tree and field nodes are stored here.  Parse_end is a dummy item
  55.  * used to free up unneeded fields without freeing the program being run 
  56.  */
  57. int errcount = 0;    /* error counter, used by yyerror() */
  58.  
  59. /* The global null string */
  60. NODE *Nnull_string;
  61.  
  62. /* The name the program was invoked under, for error messages */
  63. char *myname;
  64.  
  65. /* A block of AWK code to be run before running the program */
  66. NODE *begin_block = 0;
  67.  
  68. /* A block of AWK code to be run after the last input file */
  69. NODE *end_block = 0;
  70.  
  71. int exiting = 0;        /* Was an "exit" statement executed? */
  72. int exit_val = 0;        /* optional exit value */
  73.  
  74. #ifdef DEBUG
  75. /* non-zero means in debugging is enabled.  Probably not very useful */
  76. int debugging = 0;
  77. extern int yydebug;
  78. #endif
  79.  
  80. int tempsource = 0;        /* source is in a temp file */
  81. char **sourcefile = NULL;    /* source file name(s) */
  82. int numfiles = -1;        /* how many source files */
  83.  
  84. int strict = 0;            /* turn off gnu extensions */
  85.  
  86. NODE *expression_value;
  87.  
  88. /*
  89.  * for strict to work, legal options must be first
  90.  *
  91.  * Unfortunately, -a and -e are orthogonal to -c.
  92.  */
  93. #define EXTENSIONS    8    /* where to clear */
  94. #ifdef DEBUG
  95. char awk_opts[] = "F:f:v:caeT:CVdD";
  96. #else
  97. char awk_opts[] = "F:f:v:caeT:CV";
  98. #endif
  99.  
  100. int
  101. main(argc, argv)
  102. int argc;
  103. char **argv;
  104. {
  105. #ifdef DEBUG
  106.     /* Print out the parse tree.   For debugging */
  107.     register int dotree = 0;
  108. #endif
  109.     extern char *version_string;
  110.     FILE *fp;
  111.     int c;
  112.     extern SIGTYPE catchsig();
  113.     int i;
  114.     int nostalgia;
  115. #ifdef somtime_in_the_future
  116.     int regex_mode = RE_SYNTAX_POSIX_EGREP;
  117. #else
  118.     int regex_mode = RE_SYNTAX_AWK;
  119. #endif
  120.  
  121.     (void) signal(SIGFPE, catchsig);
  122.     (void) signal(SIGSEGV, catchsig);
  123.  
  124.     if (strncmp(version_string, "@(#)", 4) == 0)
  125.         version_string += 4;
  126.  
  127.     if ((myname = strrchr(argv[0], '.')) != NULL)
  128.         ++myname;
  129.     else
  130.     {
  131.         if (*argv[0] == '-')
  132.             myname = strchr(&argv[0][1], '-');
  133.         else
  134.             myname = strchr(argv[0], ':');
  135.  
  136.         if (myname)
  137.             ++myname;
  138.         else
  139.             myname = argv[0];
  140.     }
  141.  
  142.     if (argc < 2)
  143.         usage();
  144.  
  145.     /* initialize the null string */
  146.     Nnull_string = make_string("", 0);
  147.     Nnull_string->numbr = 0.0;
  148.     Nnull_string->type = Node_val;
  149.     Nnull_string->flags = (PERM|STR|NUM|NUMERIC);
  150.  
  151.     /* Set up the special variables */
  152.  
  153.     /*
  154.      * Note that this must be done BEFORE arg parsing else -F
  155.      * breaks horribly 
  156.      */
  157.     init_vars();
  158.  
  159.     /* worst case */
  160.     emalloc(sourcefile, char **, argc * sizeof(char *), "main");
  161.  
  162.  
  163. #ifdef STRICT    /* strict new awk compatibility */
  164.     strict = 1;
  165.     awk_opts[EXTENSIONS] = '\0';
  166. #endif
  167.  
  168. #ifndef STRICT
  169.     /* undocumented feature, inspired by nostalgia, and a T-shirt */
  170.     nostalgia = 0;
  171.     for (i = 1; i < argc && argv[i][0] == '-'; i++) {
  172.         if (argv[i][1] == '-')        /* -- */
  173.             break;
  174.         else if (argv[i][1] == 'c') {    /* compatibility mode */
  175.             nostalgia = 0;
  176.             break;
  177.         } else if (STREQ(&argv[i][1], "nostalgia"))
  178.             nostalgia = 1;
  179.             /* keep looping, in case -c after -nostalgia */
  180.     }
  181.     if (nostalgia) {
  182.         fprintf (stderr, "awk: bailing out near line 1\n");
  183.         abort();
  184.     }
  185. #endif
  186.         
  187.     while ((c = getopt (argc, argv, awk_opts)) != EOF) {
  188.         switch (c) {
  189. #ifdef DEBUG
  190.         case 'd':
  191.             debugging++;
  192.             dotree++;
  193.             break;
  194.  
  195.         case 'D':
  196.             debugging++;
  197.             yydebug = 2;
  198.             break;
  199. #endif
  200.  
  201. #ifndef STRICT
  202.         case 'c':
  203.             strict = 1;
  204.             break;
  205. #endif
  206.  
  207.         case 'F':
  208.             set_fs(optarg);
  209.             break;
  210.  
  211.         case 'f':
  212.             /*
  213.              * a la MKS awk, allow multiple -f options.
  214.              * this makes function libraries real easy.
  215.              * most of the magic is in the scanner.
  216.              */
  217.             sourcefile[++numfiles] = optarg;
  218.             break;
  219.  
  220.         case 'v':
  221.             pre_assign(optarg);
  222.             break;
  223.  
  224.         case 'V':
  225.             fprintf(stderr, "%s, patchlevel %d\n",
  226.                     version_string, PATCHLEVEL);
  227.             break;
  228.  
  229.         case 'C':
  230.             copyleft();
  231.             break;
  232.  
  233.         case 'a':    /* use old fashioned awk regexps */
  234.             regex_mode = RE_SYNTAX_AWK;
  235.             break;
  236.  
  237.         case 'e':    /* use egrep style regexps, per Posix */
  238.             regex_mode = RE_SYNTAX_POSIX_EGREP;
  239.             break;
  240.  
  241.         case 'T':    /* Specify temporary file directory */
  242.             temp_dir = optarg;
  243.             break;
  244.  
  245.         case '?':
  246.         default:
  247.             /* getopt will print a message for us */
  248.             /* S5R4 awk ignores bad options and keeps going */
  249.             break;
  250.         }
  251.     }
  252.  
  253.     /* Tell the regex routines how they should work. . . */
  254.     (void) re_set_syntax(regex_mode);
  255.  
  256. #ifdef DEBUG
  257.     setbuf(stdout, (char *) NULL);    /* make debugging easier */
  258. #endif
  259.     /* No -f option, use next arg */
  260.     /* write to temp file and save sourcefile name */
  261.     if (numfiles == -1) {
  262.         int i;
  263.  
  264.         if (optind > argc - 1)    /* no args left */
  265.             usage();
  266.         numfiles++;
  267.         i = strlen (argv[optind]);
  268.         if (i == 0) {    /* sanity check */
  269.             fprintf(stderr, "%s: empty program text\n", myname);
  270.             usage();
  271.             /* NOTREACHED */
  272.         }
  273.         sourcefile[0] = mktemp("AwkSrc");
  274.         if ((fp = fopen (sourcefile[0], "w")) == NULL)
  275.             fatal("could not save source prog in temp file");
  276.         if (fwrite (argv[optind], 1, i, fp) == 0)
  277.             fatal("could not write source program to temp file");
  278.         if (argv[optind][i-1] != '\n')
  279.             putc ('\n', fp);
  280.         (void) fclose (fp);
  281.         tempsource++;
  282.         optind++;
  283.     }
  284.     init_args(optind, argc, myname, argv);
  285.  
  286.     /* Read in the program */
  287.     if (yyparse() || errcount)
  288.         exit(1);
  289.  
  290. #ifdef DEBUG
  291.     if (dotree)
  292.         print_parse_tree(expression_value);
  293. #endif
  294.     /* Set up the field variables */
  295.     init_fields();
  296.  
  297.     if (begin_block)
  298.         (void) interpret(begin_block);
  299.     if (!exiting && (expression_value || end_block))
  300.         do_input();
  301.     if (end_block)
  302.         (void) interpret(end_block);
  303.     if (close_io() != 0 && exit_val == 0)
  304.         exit_val = 1;
  305.     exit(exit_val);
  306.     /* NOTREACHED */
  307.     return exit_val;
  308. }
  309.  
  310. static void
  311. usage()
  312. {
  313.     char *opt1 = " -f progfile [--]";
  314.     char *opt2 = " [--] 'program'";
  315. #ifdef STRICT
  316.     char *regops = " [-ae] [-F fs] [-v var=val]"
  317. #else
  318.     char *regops = " [-aecCV] [ -T dir ] [-F fs] [-v var=val]";
  319. #endif
  320.  
  321.     fprintf(stderr, "usage: %s%s%s file ...\n       %s%s%s file ...\n",
  322.         myname, regops, opt1, myname, regops, opt2);
  323.     exit(11);
  324. }
  325.  
  326. /* Generate compiled regular expressions */
  327. struct re_pattern_buffer *
  328. make_regexp(s, ignorecase)
  329. NODE *s;
  330. int ignorecase;
  331. {
  332.     struct re_pattern_buffer *rp;
  333.     char *err;
  334.  
  335.     emalloc(rp, struct re_pattern_buffer *, sizeof(*rp), "make_regexp");
  336.     memset((char *) rp, 0, sizeof(*rp));
  337.     emalloc(rp->buffer, char *, 16, "make_regexp");
  338.     rp->allocated = 16;
  339.     emalloc(rp->fastmap, char *, 256, "make_regexp");
  340.  
  341.     if (! strict && ignorecase)
  342.         rp->translate = casetable;
  343.     else
  344.         rp->translate = NULL;
  345.     if ((err = re_compile_pattern(s->stptr, s->stlen, rp)) != NULL)
  346.         fatal("%s: /%s/", err, s->stptr);
  347.     free_temp(s);
  348.     return rp;
  349. }
  350.  
  351. struct re_pattern_buffer *
  352. mk_re_parse(s, ignorecase)
  353. char *s;
  354. int ignorecase;
  355. {
  356.     char *src;
  357.     register char *dest;
  358.     register int c;
  359.     int in_brack = 0;
  360.  
  361.     for (dest = src = s; *src != '\0';) {
  362.         if (*src == '\\') {
  363.             c = *++src;
  364.             switch (c) {
  365.             case '/':
  366.             case 'a':
  367.             case 'b':
  368.             case 'f':
  369.             case 'n':
  370.             case 'r':
  371.             case 't':
  372.             case 'v':
  373.             case 'x':
  374.             case '0':
  375.             case '1':
  376.             case '2':
  377.             case '3':
  378.             case '4':
  379.             case '5':
  380.             case '6':
  381.             case '7':
  382.                 c = parse_escape(&src);
  383.                 if (c < 0)
  384.                     cant_happen();
  385.                 *dest++ = (char)c;
  386.                 break;
  387.             default:
  388.                 *dest++ = '\\';
  389.                 *dest++ = (char)c;
  390.                 src++;
  391.                 break;
  392.             }
  393.         } else if (*src == '/' && ! in_brack)
  394.             break;
  395.         else {
  396.             if (*src == '[')
  397.                 in_brack = 1;
  398.             else if (*src == ']')
  399.                 in_brack = 0;
  400.  
  401.             *dest++ = *src++;
  402.         }
  403.     }
  404.     return make_regexp(tmp_string(s, dest-s), ignorecase);
  405. }
  406.  
  407. static void
  408. copyleft ()
  409. {
  410.     extern char *version_string;
  411.     static char blurb[] =
  412. "Copyright (C) 1989, Free Software Foundation.\n\
  413. GNU Awk comes with ABSOLUTELY NO WARRANTY.  This is free software, and\n\
  414. you are welcome to distribute it under the terms of the GNU General\n\
  415. Public License, which covers both the warranty information and the\n\
  416. terms for redistribution.\n\n\
  417. You should have received a copy of the GNU General Public License along\n\
  418. with this program; if not, write to the Free Software Foundation, Inc.,\n\
  419. 675 Mass Ave, Cambridge, MA 02139, USA.\n";
  420.  
  421.     fprintf (stderr, "%s, patchlevel %d\n", version_string, PATCHLEVEL);
  422.     fputs(blurb, stderr);
  423.     fflush(stderr);
  424. }
  425.  
  426. static void
  427. set_fs(str)
  428. char *str;
  429. {
  430.     register NODE **tmp;
  431.  
  432.     tmp = get_lhs(FS_node, 0);
  433.     /*
  434.      * Only if in full compatibility mode check for the stupid special
  435.      * case so -F\t works as documented in awk even though the shell
  436.      * hands us -Ft.  Bleah!
  437.      */
  438.     if (strict && str[0] == 't' && str[1] == '\0')
  439.         str[0] = '\t';
  440.     *tmp = make_string(str, 1);
  441.     do_deref();
  442. }
  443.  
  444. static void
  445. init_args(argc0, argc, argv0, argv)
  446. int argc0, argc;
  447. char *argv0;
  448. char **argv;
  449. {
  450.     int i, j;
  451.     char *file;
  452.     NODE **aptr;
  453.  
  454.     ARGV_node = spc_var("ARGV", Nnull_string);
  455.     aptr = assoc_lookup(ARGV_node, tmp_number(0.0));
  456.     *aptr = make_string(argv0, strlen(argv0));
  457.     j = 1;
  458.     for (i = argc0; i < argc; i++) {
  459.         for (file = dirscan(argv[i]); file; file = dirscan(0)) {
  460.             aptr = assoc_lookup(ARGV_node, tmp_number((AWKNUM) j));
  461.             *aptr = make_string(file, strlen(file));
  462.             j++;
  463.         }
  464.     }
  465.     ARGC_node = spc_var("ARGC", make_number((AWKNUM) j));
  466. }
  467.  
  468. /*
  469.  * Set all the special variables to their initial values.
  470.  */
  471. static void
  472. init_vars()
  473. {
  474.     NODE **aptr;
  475.     char *var;
  476.     char buf[255];
  477.     _kernel_swi_regs regs;
  478.  
  479.     FS_node = spc_var("FS", make_string(" ", 1));
  480.     NF_node = spc_var("NF", make_number(-1.0));
  481.     RS_node = spc_var("RS", make_string("\n", 1));
  482.     NR_node = spc_var("NR", make_number(0.0));
  483.     FNR_node = spc_var("FNR", make_number(0.0));
  484.     FILENAME_node = spc_var("FILENAME", make_string("-", 1));
  485.     OFS_node = spc_var("OFS", make_string(" ", 1));
  486.     ORS_node = spc_var("ORS", make_string("\n", 1));
  487.     OFMT_node = spc_var("OFMT", make_string("%.6g", 4));
  488.     RLENGTH_node = spc_var("RLENGTH", make_number(0.0));
  489.     RSTART_node = spc_var("RSTART", make_number(0.0));
  490.     SUBSEP_node = spc_var("SUBSEP", make_string("\034", 1));
  491.     IGNORECASE_node = spc_var("IGNORECASE", make_number(0.0));
  492.  
  493.     ENVIRON_node = spc_var("ENVIRON", Nnull_string);
  494.  
  495.     /* Registers for reading OS variable values */
  496.     regs.r[0] = (int)"*";        /* All variables */
  497.     regs.r[1] = (int)buf;        /* Result buffer */
  498.     regs.r[2] = 255;        /* Length of buf */
  499.     regs.r[3] = 0;            /* Initial call  */
  500.     regs.r[4] = 3;            /* Convert result to a string */
  501.  
  502.     while (!_kernel_swi (OS_ReadVarVal, ®s, ®s) && regs.r[2] > 0)
  503.     {
  504.         var = (char *)regs.r[3];
  505.         aptr = assoc_lookup(ENVIRON_node, tmp_string(var, strlen (var)));
  506.         *aptr = make_string(buf, regs.r[2]);
  507.  
  508.         /* Restore altered registers */
  509.         regs.r[2] = 255;
  510.         regs.r[4] = 3;
  511.     }
  512. }
  513.  
  514. /* Create a special variable */
  515. static NODE *
  516. spc_var(name, value)
  517. char *name;
  518. NODE *value;
  519. {
  520.     register NODE *r;
  521.  
  522.     if ((r = lookup(variables, name)) == NULL)
  523.         r = install(variables, name, node(value, Node_var, (NODE *) NULL));
  524.     return r;
  525. }
  526.  
  527. static void
  528. pre_assign(v)
  529. char *v;
  530. {
  531.     char *cp;
  532.  
  533.     cp = strchr(v, '=');
  534.     if (cp != NULL) {
  535.         *cp++ = '\0';
  536.         variable(v)->var_value = make_string(cp, strlen(cp));
  537.     } else {
  538.         fprintf (stderr,
  539.             "%s: '%s' argument to -v not in 'var=value' form\n",
  540.                 myname, v);
  541.         usage();
  542.     }
  543. }
  544.  
  545. SIGTYPE
  546. catchsig(sig, code)
  547. int sig, code;
  548. {
  549. #ifdef lint
  550.     code = 0; sig = code; code = sig;
  551. #endif
  552.     if (sig == SIGFPE) {
  553.         fatal("floating point exception");
  554.     } else if (sig == SIGSEGV) {
  555.         msg("fatal error: segmentation fault");
  556.         /* fatal won't abort() if not compiled for debugging */
  557.         abort();
  558.     } else
  559.         cant_happen();
  560.     /* NOTREACHED */
  561. }
  562.